<template>
	<view class="history-container">
		<u-navbar title="历史记录" :is-back="true" back-icon-color="#ffffff" title-color="#ffffff" :background="{ background: '#1a4380' }"></u-navbar>
		
		<view class="filter-bar">
			<view class="date-picker">
				<picker mode="date" :value="startDate" @change="onStartDateChange">
					<view class="picker-item">
						<text>开始：</text>
						<text class="date-text">{{startDate || '选择日期'}}</text>
						<text class="iconfont icon-calendar"></text>
					</view>
				</picker>
				<text class="separator">至</text>
				<picker mode="date" :value="endDate" @change="onEndDateChange">
					<view class="picker-item">
						<text>结束：</text>
						<text class="date-text">{{endDate || '选择日期'}}</text>
						<text class="iconfont icon-calendar"></text>
					</view>
				</picker>
			</view>
			<view class="search-btn" @click="searchRecords">
				<text class="iconfont icon-search"></text>
				<text>搜索</text>
			</view>
		</view>

		<view class="patrol-list" v-if="patrolList.length > 0">
			<view class="patrol-item" v-for="(item, index) in patrolList" :key="index" @click="goToDetail(item.id)">
				<view class="patrol-header">
					<text class="patrol-title">{{item.title}}</text>
					<text class="patrol-status" :class="item.status === 0 ? 'status-normal' : 'status-abnormal'">{{item.status === 0 ? '正常' : '异常'}}</text>
				</view>
				<view class="patrol-info">
					<view class="info-item">
						<text class="label">巡查时间：</text>
						<text class="value">{{item.patrolTime}}</text>
					</view>
					<view class="info-item">
						<text class="label">巡查地点：</text>
						<text class="value">{{item.location}}</text>
					</view>
					<view class="info-item">
						<text class="label">巡查人员：</text>
						<text class="value">{{item.patrolPerson}}</text>
					</view>
				</view>
				<view class="patrol-issues" v-if="item.issues && item.issues.length > 0">
					<text class="issues-title">发现问题：</text>
					<text class="issues-content">{{item.issues}}</text>
				</view>
				<view class="patrol-footer">
					<view class="patrol-tags">
						<text class="tag" v-for="(tag, tagIndex) in item.tags" :key="tagIndex">{{tag}}</text>
					</view>
					<view class="patrol-more">
						<text class="iconfont icon-arrow-right"></text>
					</view>
				</view>
			</view>
		</view>
		
		<view class="empty-state" v-else>
			<image src="/static/empty.png" mode="widthFix" class="empty-image"></image>
			<text class="empty-text">暂无巡查记录</text>
		</view>
		
		<u-loadmore :status="loadMoreStatus" v-if="patrolList.length > 0"></u-loadmore>
		
		<u-toast ref="uToast"></u-toast>
		<u-popup :show="showFilter" mode="bottom" @close="closeFilter">
			<view class="filter-popup">
				<view class="filter-header">
					<text class="cancel" @click="closeFilter">取消</text>
					<text class="title">筛选</text>
					<text class="confirm" @click="applyFilter">确定</text>
				</view>
				<scroll-view scroll-y class="filter-content">
					<view class="filter-section">
						<text class="section-title">巡查状态</text>
						<view class="filter-options">
							<view class="filter-option" 
								  v-for="(status, sIndex) in statusOptions" 
								  :key="sIndex"
								  :class="{ active: selectedStatus === status.value }"
								  @click="selectedStatus = status.value">
								<text>{{status.label}}</text>
							</view>
						</view>
					</view>
					
					<view class="filter-section">
						<text class="section-title">巡查区域</text>
						<view class="filter-options">
							<view class="filter-option" 
								  v-for="(area, aIndex) in areaOptions" 
								  :key="aIndex"
								  :class="{ active: selectedArea === area.value }"
								  @click="selectedArea = area.value">
								<text>{{area.label}}</text>
							</view>
						</view>
					</view>
				</scroll-view>
			</view>
		</u-popup>
	</view>
</template>

<script>
export default {
	data() {
		return {
			startDate: '',
			endDate: '',
			patrolList: [],
			page: 1,
			pageSize: 10,
			total: 0,
			loadMoreStatus: 'loading', // loading, nomore, loadmore
			showFilter: false,
			selectedStatus: -1,
			selectedArea: '',
			statusOptions: [
				{ label: '全部', value: -1 },
				{ label: '正常', value: 0 },
				{ label: '异常', value: 1 }
			],
			areaOptions: [
				{ label: '全部', value: '' },
				{ label: '教学楼', value: '教学楼' },
				{ label: '宿舍楼', value: '宿舍楼' },
				{ label: '食堂', value: '食堂' },
				{ label: '图书馆', value: '图书馆' },
				{ label: '操场', value: '操场' }
			]
		}
	},
	onLoad() {
		// 初始化日期为当前月的第一天和最后一天
		const now = new Date()
		const year = now.getFullYear()
		const month = now.getMonth() + 1
		
		this.startDate = `${year}-${month.toString().padStart(2, '0')}-01`
		this.endDate = this.getLastDayOfMonth(year, month)
		
		this.getPatrolHistory()
	},
	onReachBottom() {
		if (this.loadMoreStatus === 'loadmore') {
			this.page++
			this.getPatrolHistory(true)
		}
	},
	methods: {
		// 获取巡查历史记录
		getPatrolHistory(isLoadMore = false) {
			// 重置列表
			if (!isLoadMore) {
				this.page = 1
				this.patrolList = []
			}
			
			// 显示加载中
			if (this.page === 1) {
				uni.showLoading({ title: '加载中' })
			}
			
			// 设置加载状态
			this.loadMoreStatus = 'loading'
			
			// 模拟接口请求
			setTimeout(() => {
				uni.hideLoading()
				
				// 模拟数据
				const mockData = []
				for (let i = 0; i < this.pageSize; i++) {
					const randomStatus = Math.random() > 0.7 ? 1 : 0
					const id = (this.page - 1) * this.pageSize + i + 1
					mockData.push({
						id: `patrol-${id}`,
						title: `${this.getRandomArea()}巡查记录`,
						status: randomStatus,
						patrolTime: this.getRandomDate(this.startDate, this.endDate),
						location: this.getRandomArea(),
						patrolPerson: this.getRandomPerson(),
						issues: randomStatus === 1 ? this.getRandomIssue() : '',
						tags: this.getRandomTags()
					})
				}
				
				// 添加到列表
				this.patrolList = [...this.patrolList, ...mockData]
				
				// 设置总数据量
				this.total = 35
				
				// 设置加载状态
				if (this.patrolList.length >= this.total) {
					this.loadMoreStatus = 'nomore'
				} else {
					this.loadMoreStatus = 'loadmore'
				}
			}, 1000)
		},
		
		// 开始日期变化
		onStartDateChange(e) {
			this.startDate = e.detail.value
		},
		
		// 结束日期变化
		onEndDateChange(e) {
			this.endDate = e.detail.value
		},
		
		// 搜索记录
		searchRecords() {
			if (!this.startDate || !this.endDate) {
				this.$refs.uToast.show({
					type: 'error',
					message: '请选择开始和结束日期'
				})
				return
			}
			
			if (new Date(this.startDate) > new Date(this.endDate)) {
				this.$refs.uToast.show({
					type: 'error',
					message: '开始日期不能大于结束日期'
				})
				return
			}
			
			this.getPatrolHistory()
		},
		
		// 跳转到详情
		goToDetail(id) {
			uni.navigateTo({
				url: `/pages/patrol/detail?id=${id}`
			})
		},
		
		// 打开筛选
		openFilter() {
			this.showFilter = true
		},
		
		// 关闭筛选
		closeFilter() {
			this.showFilter = false
		},
		
		// 应用筛选
		applyFilter() {
			this.closeFilter()
			this.getPatrolHistory()
		},
		
		// 获取月份最后一天
		getLastDayOfMonth(year, month) {
			const date = new Date(year, month, 0)
			return `${year}-${month.toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
		},
		
		// 随机生成区域
		getRandomArea() {
			const areas = ['主教学楼', '二教学楼', '图书馆', '1号宿舍楼', '2号宿舍楼', '第一食堂', '第二食堂', '操场', '篮球场', '实验楼']
			return areas[Math.floor(Math.random() * areas.length)]
		},
		
		// 随机生成人员
		getRandomPerson() {
			const persons = ['张三', '李四', '王五', '赵六', '钱七', '孙八']
			return persons[Math.floor(Math.random() * persons.length)]
		},
		
		// 随机生成问题
		getRandomIssue() {
			const issues = [
				'发现电线老化现象，存在安全隐患',
				'消防设备缺失，需要及时补充',
				'发现墙壁裂缝，建议检查修复',
				'楼道堆放杂物，影响通行',
				'发现水管漏水情况，需及时处理'
			]
			return issues[Math.floor(Math.random() * issues.length)]
		},
		
		// 随机生成标签
		getRandomTags() {
			const allTags = ['日常巡查', '安全检查', '防火检查', '设备检查', '卫生检查', '电气检查']
			const count = Math.floor(Math.random() * 3) + 1
			const result = []
			
			for (let i = 0; i < count; i++) {
				const randomIndex = Math.floor(Math.random() * allTags.length)
				if (!result.includes(allTags[randomIndex])) {
					result.push(allTags[randomIndex])
				}
			}
			
			return result
		},
		
		// 在日期范围内随机生成日期
		getRandomDate(start, end) {
			const startDate = new Date(start)
			const endDate = new Date(end)
			const randomDate = new Date(startDate.getTime() + Math.random() * (endDate.getTime() - startDate.getTime()))
			
			const year = randomDate.getFullYear()
			const month = (randomDate.getMonth() + 1).toString().padStart(2, '0')
			const day = randomDate.getDate().toString().padStart(2, '0')
			const hour = Math.floor(Math.random() * 24).toString().padStart(2, '0')
			const minute = Math.floor(Math.random() * 60).toString().padStart(2, '0')
			
			return `${year}-${month}-${day} ${hour}:${minute}`
		}
	}
}
</script>

<style lang="scss" scoped>
.history-container {
	min-height: 100vh;
	background-color: #f8f8f8;
	
	.filter-bar {
		background-color: #fff;
		padding: 20rpx 30rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
		
		.date-picker {
			display: flex;
			align-items: center;
			flex: 1;
			
			.picker-item {
				display: flex;
				align-items: center;
				font-size: 26rpx;
				
				.date-text {
					color: #1a4380;
					margin: 0 10rpx;
				}
				
				.iconfont {
					color: #999;
					font-size: 28rpx;
				}
			}
			
			.separator {
				margin: 0 20rpx;
				color: #999;
			}
		}
		
		.search-btn {
			background-color: #1a4380;
			color: #fff;
			padding: 10rpx 30rpx;
			border-radius: 30rpx;
			font-size: 26rpx;
			display: flex;
			align-items: center;
			
			.iconfont {
				margin-right: 10rpx;
			}
		}
	}
	
	.patrol-list {
		padding: 20rpx;
		
		.patrol-item {
			background-color: #fff;
			border-radius: 12rpx;
			padding: 20rpx;
			margin-bottom: 20rpx;
			box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
			
			.patrol-header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding-bottom: 20rpx;
				border-bottom: 1px solid #f5f5f5;
				
				.patrol-title {
					font-size: 32rpx;
					font-weight: bold;
					color: #333;
				}
				
				.patrol-status {
					font-size: 26rpx;
					padding: 4rpx 16rpx;
					border-radius: 30rpx;
					
					&.status-normal {
						background-color: #e7f5ef;
						color: #19be6b;
					}
					
					&.status-abnormal {
						background-color: #fff2f0;
						color: #fa3534;
					}
				}
			}
			
			.patrol-info {
				padding: 20rpx 0;
				
				.info-item {
					display: flex;
					margin-bottom: 10rpx;
					
					.label {
						color: #666;
						font-size: 28rpx;
						width: 180rpx;
					}
					
					.value {
						color: #333;
						font-size: 28rpx;
						flex: 1;
					}
				}
			}
			
			.patrol-issues {
				background-color: #fafafa;
				padding: 20rpx;
				border-radius: 8rpx;
				margin-bottom: 20rpx;
				
				.issues-title {
					color: #fa3534;
					font-size: 28rpx;
					font-weight: bold;
					margin-bottom: 10rpx;
				}
				
				.issues-content {
					color: #333;
					font-size: 28rpx;
				}
			}
			
			.patrol-footer {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding-top: 10rpx;
				
				.patrol-tags {
					display: flex;
					flex-wrap: wrap;
					
					.tag {
						background-color: #f5f5f5;
						color: #666;
						font-size: 24rpx;
						padding: 6rpx 16rpx;
						border-radius: 30rpx;
						margin-right: 10rpx;
						margin-bottom: 10rpx;
					}
				}
				
				.patrol-more {
					.iconfont {
						color: #999;
						font-size: 32rpx;
					}
				}
			}
		}
	}
	
	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding-top: 200rpx;
		
		.empty-image {
			width: 300rpx;
			margin-bottom: 30rpx;
		}
		
		.empty-text {
			color: #999;
			font-size: 28rpx;
		}
	}
	
	.filter-popup {
		.filter-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 30rpx;
			border-bottom: 1px solid #f5f5f5;
			
			.title {
				font-size: 32rpx;
				font-weight: bold;
				color: #333;
			}
			
			.cancel {
				color: #999;
				font-size: 28rpx;
			}
			
			.confirm {
				color: #1a4380;
				font-size: 28rpx;
			}
		}
		
		.filter-content {
			max-height: 700rpx;
			
			.filter-section {
				padding: 30rpx;
				
				.section-title {
					font-size: 28rpx;
					color: #333;
					font-weight: bold;
					margin-bottom: 20rpx;
				}
				
				.filter-options {
					display: flex;
					flex-wrap: wrap;
					
					.filter-option {
						padding: 10rpx 30rpx;
						background-color: #f5f5f5;
						border-radius: 30rpx;
						margin-right: 20rpx;
						margin-bottom: 20rpx;
						font-size: 26rpx;
						color: #666;
						
						&.active {
							background-color: #e7f1ff;
							color: #1a4380;
						}
					}
				}
			}
		}
	}
}
</style> 